/**
 * Code based on the Turntable.fm API by Alain Gilbert: https://github.com/alaingilbert/Turntable-API
 * 
 * All custom logic created by Brian Johnson. No guarantees are made regarding the workability,
 * flexibility, reliability or any other functionality of this code. Use at your own risk.
 *
 */

	var Bot = require('./index.js');
	var botDjName=process.argv[2];//console.log(process.argv[2]); //node bot.js [botDjName] [roomName]
	var roomName=process.argv[3];//console.log(process.argv[3]); //node bot.js [botDjName] [roomName]
	var botConfig = require('./botConfig.js').botConfig(botDjName,roomName);
	var bot = new Bot(botConfig.auth, botConfig.userid, botConfig.roomid);
	var USERID=botConfig.userid;
	var ROOMID=botConfig.roomid;
	
	$g={};//build governor object and define global vars

	$g.totalAwesomeCount=0;
    $g.announceSongStats=botConfig.songstats;

	//$g.botUserCount=[];//array to capture current room attendance [djs,listeners,total,minVote]
	$g.arrayAwesomeVotePlaced=[];//keeps track of voters for minVote feature
	$g.songSnaggers=[];//array to capture number of song snags 
	$g.downVoteArray=[];//array to keep track of lamers	
	$g.botAdmins=[];//array to specify bot admins
	if(botConfig.admin) {
		var aryBotConfigAdmins=botConfig.admin.split(",");
		for(var i=0;i<aryBotConfigAdmins.length;i++){
			$g.botAdmins.push(aryBotConfigAdmins[i]);
		}
	}

	//get array of available room themes
	$g.arrayRoomThemes=botConfig.themes;
	$g.roomTheme=$g.arrayRoomThemes[botConfig.defaulttheme];
    $g.greeting=botConfig.defaultgreet;
    $g.djOverride=botConfig.djoverride;

	$g.availableBotCommands=['commands',' bot?',' mods',' cheers'];
	if(botConfig.vote) {
		$g.availableBotCommands.push(" awesome");
		$g.availableBotCommands.push(" +");
		$g.availableBotCommands.push(" +1");
		$g.availableBotCommands.push(" bop");
		$g.availableBotCommands.push(" dance");
	}
	if(botConfig.djq) { $g.availableBotCommands.push(" q+");$g.availableBotCommands.push(" q-");$g.availableBotCommands.push(" q?"); }
	if(botConfig.lottery) { $g.availableBotCommands.push(" pb");$g.availableBotCommands.push(" lotto");$g.availableBotCommands.push(" mega");$g.availableBotCommands.push(" roulette"); }
	if(botConfig.theme) { $g.availableBotCommands.push(" theme?"); }
	if(botConfig.rps) { $g.availableBotCommands.push(" rps");$g.availableBotCommands.push(" rpsls"); }
	if(botConfig.coinflip) { $g.availableBotCommands.push(" flip");$g.availableBotCommands.push(" coinflip"); }
	if(botConfig.eightball) { $g.availableBotCommands.push(" 8ball [question]"); }
	if(botConfig.fortune) { $g.availableBotCommands.push(" fortune"); }
	if(botConfig.dive) { $g.availableBotCommands.push(" dive"); }
    
    if(botConfig.greet) { 
        $g.greet=true;
        $g.greetloc=botConfig.greetloc;
    } else { $g.greet=false; }
    if(botConfig.qinterval) {
        $g.qinterval=botConfig.qinterval*1000;
    } else {
        $g.qinterval=5000;
    }
    
	//banned users:
	$g.bannedUsers=[];
	//$g.bannedUsers.push('4ec0f754a3f75102f700180b');//Theoduric the Gringo
		
	battle={};//build battle object
	
	bot.name = botConfig.name;
	bot.on('ready', function(data) {
		bot.userInfo(function(data) {
			bot.name = data.name;
			$g.numVotesToAwesome=0;
			$g.getUserCount();
		});
	});
	
	bot.on('registered', function(data) {
        var djName=data.user[0].name;
        var djId=data.user[0].userid;

		$g.getUserCount();
		$g.bootBanned(data.user[0].userid);//check for/boot banned user on entry
        if($g.greet) {
            if($g.greetloc=="chat" || $g.greetloc=="both") {
                bot.speak('@'+djName+' '+$g.greeting);
            }
            if($g.greetloc=="pm" || $g.greetloc=="both") {
                bot.pm($g.greeting,djId);
            }
        }
	});

	
	bot.on('newsong', function (data) {
		$g.arrayAwesomeVotePlaced=[];
		var metadata = data.room.metadata;
		
        $g.currentSong=metadata.current_song._id;
        
		$g.songAlreadyAwesomed=false;
		$g.getUserCount();
		$g.numVotesToAwesome=0;
		$g.songSnaggers=[];
		
		//if only 1 dj, check to see if i am on stage.  if not, add me.
		if(!$g.djOverride) { //if $g.djOverride=false
			if(metadata.djcount<2) { //how many djs?
				if(metadata.djs.indexOf(USERID)<0) {  //am i on stage?
					bot.addDj();
				}
			}
			
			//if 3+ djs, check to see if i am on stage.  if so, remove me.
			if(metadata.djcount>2) { 
				if(metadata.djs.indexOf(USERID)>-1) {  //am i on stage?
					bot.remDj();
				}
			}
		}
	});
	
	bot.on('endsong', function (data) {
		var songId=(data.room.metadata.current_song) ? data.room.metadata.current_song._id : "";
		var songName=(data.room.metadata.current_song) ? data.room.metadata.current_song.metadata.song : "";
		var songArtist=(data.room.metadata.current_song) ? data.room.metadata.current_song.metadata.artist : "";
		var songAlbum=(data.room.metadata.current_song) ? data.room.metadata.current_song.metadata.album : "";
		var djName=(data.room.metadata.current_song) ? data.room.metadata.current_song.djname : "";
		var upVotes=data.room.metadata.upvotes;
		var downVotes=data.room.metadata.downvotes;
		var listenerCount=data.room.metadata.listeners-1;
		var pctAwesome=upVotes/listenerCount*100;
		var snags=$g.songSnaggers.length;
		var djId=data.room.metadata.current_dj;
		var firstDjId=data.room.metadata.djs[0];
		var djCount=data.room.metadata.djcount;
		var djs=data.room.metadata.djs; //array
		var displayUpVotes;
		
		if($g.announceSongStats) {
		
			if(upVotes) {
				var tempDisplayUpVotes=upVotes+"";
				displayUpVotes="";
				for(var i=0;i<tempDisplayUpVotes.length;i++) {
					displayUpVotes+=tempDisplayUpVotes[i];
				}
			}

			if(!battle.inProgress) {
				if("undefined" == typeof(displayUpVotes) || displayUpVotes=='undefined' || displayUpVotes=="") { displayUpVotes='0'; }	
				bot.speak('Song: '+songName+' | Artist: '+songArtist+' | DJ: '+djName+' | Votes: '+displayUpVotes);			
			}
						
			//bot.roomInfo(false,function(roomData){
			//	var voters=roomData.room.metadata.votelog;
			//	for(var ii=0;ii < voters.length; ii++) {
			//		/*console.log(voters[ii][0]+' - '+voters[ii][1]);*/
			//	}
			//});			
			
			if(data.room.metadata.downvotes>0) {
				var theNameArray = [ 'joker', 'knucklehead', 'chucklehead', 'clown', 'good-for-nothing', 'scoundrel', 'schmuck', 'rascal', 'punk' ]    
				var theName = theNameArray[Math.floor(Math.random() * theNameArray.length)];
				
				(downVotes==1) ? theName=theName : theName=theName+'s';
				bot.speak('@'+djName+' Just so you know, '+downVotes+' '+theName+' lamed your song.');
				
				/*console.log('downVoteArray: '+$g.downVoteArray);//populated on update_votes*/
				$g.downVoteArray=[];//clear out array
			}
		}
		
		
		if(botConfig.autosnag) {
            if(pctAwesome>=botConfig.snagpct){
                $g.snag(songId);
                bot.speak(songName+' is so good, I\'m adding it to my queue!');
            }
		}
	
		//slide
		var djDeckPosition=djs.indexOf(djId);
		$g.slide(djId,djDeckPosition,djName);
		if($g.slideOn) { $g.slideCurrentStats(); }
		
		if(battle.inProgress) {
			for(var i=0;i < battle.djs.length; i++) {
				if(data.room.metadata.current_song.djid==battle.djs[i][1]) {
					if(battle.djs[i][7]>-1 && battle.djs[i][7]<battle.maxRounds+1) {
						battle.djs[i][7]=battle.djs[i][7]+1;//song count
						
						//battle.djs[i][2]=data.room.metadata.current_song.djname;//dj name
						battle.djs[i][3]=battle.djs[i][3]+upVotes;//total awesome count
						battle.djs[i][4]=battle.djs[i][4]+downVotes;//total lame count
						battle.djs[i][5]=battle.djs[i][5]+snags;//total snag count
						battle.djs[i][6]=battle.djs[i][6]+((upVotes-downVotes)+(2*snags));//total points
						
						//console.log('room id: '+	battle.djs[i][0]);
                        
						/*
                        console.log('dj id: '+		battle.djs[i][1]);
						console.log('dj name: '+	battle.djs[i][2]);
						console.log('awesomes: '+	battle.djs[i][3]);
						console.log('lames: '+		battle.djs[i][4]);
						console.log('snags: '+		battle.djs[i][5]);
						console.log('points: '+		battle.djs[i][6]);
						console.log('songs: '+		battle.djs[i][7]);
						*/
                        
						if(battle.djs[i][7]==battle.maxRounds) {
							battle.djsFinished=battle.djsFinished+1;
							/*console.log('Battle rounds complete for: '+battle.djs[i][2]);*/
							battle.djs[i][8]=true; //dj has completed all battle rounds
							bot.speak('@'+battle.djs[i][2]+' Congrats! You finished the battle with '+battle.djs[i][6]+'pts on '+battle.djs[i][7]+' turns!')
						
							if(battle.djsFinished==battle.djs.length) {
								//var message='That\'s it! The battle is over! PM "battle|stats" to '+bot.name+' to get results.';
								//bot.speak(message);
								bot.speak("FINAL BATTLE STATS: ");
								setTimeout(function(){
									battle.stats('',true,true);//no sender id, isPublic, isFinal
								},500);

								/*console.log(message);*/
								battle.inProgress=false;
								battle.complete=true;
							}
						} else {
							bot.speak('@'+battle.djs[i][2]+' - After '+battle.djs[i][7]+' round(s), you\'re looking good with '+battle.djs[i][6]+' battle points! PM battle|stats to '+bot.name+' for current standings.');
						}	
					}
				}
			}
		}
	});

	bot.on('update_votes',function(data) {
		var voteLog=data.room.metadata.votelog;
		for (var i=0;i < voteLog.length; i++) {
		  if(voteLog[i][1]=='down') {
			if($g.downVoteArray.indexOf(voteLog[i][0])<0) {
				$g.downVoteArray.push(voteLog[i][0]);
			}
		  } else {
			if($g.downVoteArray.indexOf(voteLog[i][0])>-1) {
				$g.downVoteArray.splice($g.downVoteArray.indexOf(voteLog[i][0]),1);
			}
		  }
		}
	});
	
	bot.on('deregistered',function(data) {
		var userId=data.user[0].userid;

		//remove user from dj queue
		if($g.djQueue) {
			if($g.djQueue.length>0) {
				for(var i=0;i<$g.djQueue.length;i++) {
					if($g.djQueue[i][0]==userId) {
						$g.djQueue.splice(i,1);
						break;
					}
				}
			}
		}
	});

    $g.queueCallingNextDj = function() {
        var queueMessage;
        if($g.queueAlertNextInLineCount==0) {
            queueMessage='@'+$g.djQueue[0][1]+' Your turn to DJ is here! Hop on up!';
            bot.speak(queueMessage);
            $g.queueAlertNextInLineCount=$g.queueAlertNextInLineCount+1
        } else if($g.queueAlertNextInLineCount==1) {
            queueMessage='@'+$g.djQueue[0][1]+' Last warning. Take your spot now or you lose it!';
            bot.speak(queueMessage);
            $g.queueAlertNextInLineCount=$g.queueAlertNextInLineCount+1
        } else if($g.queueAlertNextInLineCount==2) {
            queueMessage='@'+$g.djQueue[0][1]+' Sorry, but you lost your spot. (You snooze, you lose!) Type /q+ to get back in the queue.';
            $g.queueAlertNextInLineCount=0;
            $g.djQueue.splice(0,1);
            clearInterval($g.queueInterval);
            if($g.djQueue.length>0) {
                $g.queueInterval=setInterval(function(){$g.queueCallingNextDj()},$g.qinterval);
            } else {
                /* nothing for now */
            }
            bot.speak(queueMessage);
        } else if($g.queueAlertNextInLineCount>2) {
            $g.queueAlertNextInLineCount=0
            clearInterval($g.queueInterval);
        }
    }
    
	bot.on('rem_dj',function(data) {
		var queueMessage;
		var message;
		var queueReminderCount=0;
		
		if($g.djQueue) {
			if($g.djQueue.length>0) {
                $g.queueAlertNextInLineCount=0
                $g.queueCallingNextDj();
                //$g.queueInterval=setInterval(function(){$g.queueCallingNextDj()},$g.qinterval);
	
				/*console.log('DJ QUEUE: Next up is '+$g.djQueue[0][1]);*/
			} else {
				/*console.log('dj queue is on, but no one is in the queue - turn it off?');*/
			}
		}
		
		if($g.slideOn) { //remove dj from slide array if they leave tables before completing available turns
			var djSlideIndex=$g.slideGetDjIndex(data.user[0].userid);
			if(djSlideIndex>-1) { $g.slideCountArray.splice(djSlideIndex,1); }
		}
		
		if(battle.djs) { //any dj who leaves the tables during a battle is removed from the battle
			for(var i=0;i<battle.djs.length;i++) {
				if(battle.djs[i][1]==data.user[0].userid) {
					if(!battle.djs[i][8]) { //don't remove dj from battle if they have completed all rounds
						message="@"+data.user[0].name+' left the battle early. That\'s a forfeit in my book. '+
							'The odds of winning just improved for everyone else!';
						bot.speak(message);
						battle.djs.splice([i],1);
					}
				}
			}
		}
	});
    
    $g.queueGetNext=function(pv_djId,pv_djName) {
        var djId=pv_djId;
        var djName=pv_djName;
        var remDjFound=false;
        
		if($g.djQueue) { //if there is a dj queue, check if new dj is next in line
			if($g.djQueue.length>0) {
				if($g.djQueue[0][0]!=djId) {
					var nextDjName=$g.djQueue[0][1];
	
					bot.speak('@'+djName+' - Wait your turn. There is a DJ queue, and you are NOT next.'+
						' Type /q? to see who\'s next, or /q+ to get in line.');
					bot.speak('@'+nextDjName+': Please step up.');
					
					bot.remDj(djId,function(empty) {						
						if(!$g.arrayRemDj) { $g.arrayRemDj=[]; }
						for(var i=0;$g.arrayRemDj.length;i++) {
							if($g.arrayRemDj[i]) {
								if($g.arrayRemDj[i][0]==djId) { remDjFound=true;remDjIndex=i;break; }
							}
						}
						if(remDjFound) { 
							$g.arrayRemDj[remDjIndex][1]=$g.arrayRemDj[remDjIndex][1]+1; 
						} else {
							remDjIndex=$g.arrayRemDj.length;
							$g.arrayRemDj.push([djId,1]);
						}
						if($g.arrayRemDj[remDjIndex][1]>2) {
							bot.boot(djId,function(data) {
								$g.arrayRemDj.splice(remDjIndex,1);
								/*console.log('DJ Booted: Queue violation ('+djName+')');*/
							});
						}
					});
				} else {
					$g.djQueue.splice(0,1);
					if($g.djQueue.length>0) { bot.speak('@'+$g.djQueue[0][1]+' - Get ready.  You\'re next!'); }
					if($g.arrayRemDj) { 
						//for(var i=0;$g.arrayRemDj.length;i++) {
							//if($g.arrayRemDj[i][0]==djId) { $g.arrayRemDj.splice(i,1); console.log('good to go'); }
						//}
					}
				}
			}
		}
    }
    
	bot.on('add_dj',function(data) {
		var arrayUsers=data.user.splice(',');
		var djId=arrayUsers[0].userid;
		var djName=arrayUsers[0].name;
		var djInfo=djId+'|'+djName;
		var theQueue;
		var remDjIndex;
		
        //if new dj is not next in queue, don't let them up, but don't update the queue yet
        $g.queueGetNext(djId,djName);
	});
		
	bot.on('speak', function (data) {
        var message;
        var name = data.name;
        var userId= data.userid;
        var originalText=data.text;
        var text = originalText.toLowerCase();
        text=text.replace(/^\//,"");
        
		//was the pm from a room moderator?
		if($g.mods) { ($g.mods.indexOf(data.userid)>-1) ? $g.isMod=true : $g.isMod=false; } 
		if($g.botAdmins) { ($g.botAdmins.indexOf(data.userid)>-1) ? $g.isBotAdmin=true : $g.isBotAdmin=false; } 

        if(botConfig.chatlog) { console.log('('+name+') '+text); }

        if(botConfig.reqbotname) {
            //split at first space
            var botName=text.substring(0,text.indexOf(" "));
            
            //check to see if botConfig.cmdname==[bot name passed in]
            if(botName==botConfig.cmdname) {
                //if yes...
                text=text.substring(text.indexOf(" ")+1,text.length);
            } else {
                //if no, set text="botnamefail" (or something similar!)
                text="bot name required; provided name does not match";
            }
        }
        
        //modify value of text to match specific switch/case values
        if(text.match(/^8ball/)) { text='8ball'; } //strip off actual magic8ball question

		switch(text) {
            case "dive":
                if(botConfig.dive) {
                    bot.remDj(userId,function(empty) {
                        /*nothing*/
                    });
                }
                break;
			case "awesome": case "+1": case "+": case "bop": case "dance":
				if(botConfig.vote) {
					if(!$g.songAlreadyAwesomed) {
						if($g.arrayAwesomeVotePlaced.indexOf(userId)<0) {
							$g.arrayAwesomeVotePlaced.push(userId);
							$g.numVotesToAwesome+=1;
							var votesToGo=$g.botUserCount[3]-$g.numVotesToAwesome;
							var singPlural=(votesToGo==1) ? '' : 's';
							
							if($g.numVotesToAwesome>=$g.botUserCount[3]) {							
								var theAwesomeMsgArray = [ 
									'This song is awesome!','One awesome, coming up!','Good idea! +1 awesome from me!',
									'Really? You like this song? OK. I\'ll awesome it for you.','Talk about good taste in music!',
									'I\'ll :beer: to that!','I\'ll :cocktail: to that!','That\'s a :whale: of an idea!',
									'Winner winner chicken dinner!','It\'s not Gangnam Style, but you\'re right... It is awesome!',
									'Ok, ok, ok. I\'ll awesome the song. @'+name+' can be so demanding!'
								]    
								var theAwesomeMsg = theAwesomeMsgArray[Math.floor(Math.random() * theAwesomeMsgArray.length)];
								bot.speak(theAwesomeMsg);
								$g.songAlreadyAwesomed=true;
		
								$g.totalAwesomeCount=$g.totalAwesomeCount+1;
							  bot.vote('up');
							} else {
								bot.speak('Almost there, only '+votesToGo+' more vote'+singPlural+' until I awesome this song!');
							}
						} else {
							var singPlural=(votesToGo==1) ? '' : 's';bot.speak('@'+name+' - You already voted! I need someone else to vote before I awesome the song!');
						}
					}
				}
			  break;
			case "thirsty":
				bot.speak('@'+name+' - If you\'re thirsty, have some :beers:!');
				break;
			case "cheers":
				bot.speak('@'+name+' - I raise my :beer: to you!');
				break;
			case "fortune":
				if(botConfig.fortune) {
					bot.speak('@'+name+' - '+$g.getFortune());
				}
				break;
			case "8ball":
				if(botConfig.eightball) {
					bot.speak('@'+name+' - :8ball: - '+$g.magic8ball());
				}
				break;
			case "rps": //rock,paper,scissors
				if(botConfig.rps) {
					bot.speak('@'+name+' - '+$g.rps());
				}
				break;
			case "rpsls": //rock,paper,scissors,lizard,spock
				if(botConfig.rps) {
					bot.speak('@'+name+' - '+$g.rpsls());
				}
				break;
			case "flip": case "coinflip":
				if(botConfig.coinflip) {
					bot.speak('@'+name+' - '+$g.coinFlip());
				}
				break;
			case "mega": //get mega millions numbers
				if(botConfig.lottery) {
					bot.speak('@'+name+' '+$g.getLotto(56,46,'MB')); //1-56 for white balls, 1-46 for mega ball
				}
				break;
			case "pb": //get powerball numbers
				if(botConfig.lottery) {
					bot.speak('@'+name+' '+$g.getLotto(59,35,'PB')); //1-59 for white balls, 1-35 for powerball
				}
				break;
			case "lotto": //get random lotto numbers
				if(botConfig.lottery) {
					bot.speak('@'+name+' '+$g.getLotto(60,1)); //1-59 for white balls, 1-35 for powerball
				}
				break;
			case "roulette":
				if(botConfig.lottery) {
					bot.speak('@'+name+' '+$g.getRoulette()); 
				}
				break;
            case "auto?": //get link to auto-awesome script
                bot.speak('Get your auto-awesome script here: http://goo.gl/tiMzq');
				break;
			case "mods":
				$g.getMods();
				break;
			//case "last 10": case "last10": case "last":
			//	$g.getLast(10);
			//	break;
			case "links":
				bot.speak('@'+name+' '+$g.getLinks());
				break;
			case 'current theme': case 'currenttheme': case 'theme?': case 'room theme':
				if(botConfig.theme) {
					$g.getRoomTheme();
				}
				break;
			case "q+":
				if(botConfig.djq) {
					if($g.isQueue) {
						console.log($g.isDjing(data.userid));
						if($g.isDjingReturnVal) {
							message='@'+name+' - You can\'t add yourself to the queue when your\'re already DJ\'ing!';
						} else {
							var queuePosition=$g.queueAdd(data.userid,name);//add to queue and get current position
							queuePosition=queuePosition.split('|');
							
							switch(queuePosition[0]) { 
								case 'new':	message='@'+name+' has been added to the DJ queue.';break; //dj added
								case 'existing': message='@'+name+' is already in the DJ queue.'; break;//dj already in queue at # position
								case 'dj':	message='@'+name+' is already on the DJ stand!'; queuePosition[1]='-1';break;
							}
							
							switch(queuePosition[1]) {
								case '-1':	break;
								case '0':	message=message+' Get ready! The next open spot is reserved for you!';break;
								case '1':	message=message+' Only 1 more DJ stands between you and Turntable fame!';break;
								default:	message=message+' There are '+queuePosition[1]+' more DJ\'s in front of you.';break;
							}
						}
						/*console.log(message);*/
						bot.speak(message);
					} else {
						bot.speak('@'+name+' - There is currently no DJ queue.')
					}
				}
				break;
			case "slide?":
				if(botConfig.slide) {
					var returnVal;
					if($g.slideOn) {
						returnVal=$g.slideCurrentStats();
					} else {
						returnVal="Slide is currently disabled."	
					}
					if(returnVal) { bot.speak(returnVal); }
				}
				break;
			case "q-":
				if(botConfig.djq) {
					if($g.isQueue) {
						var queueRemove=$g.queueRemove(data.userid,name);
						bot.speak('@'+name+' has been removed from the DJ queue.');
					} else {
						bot.speak('@'+name+' - There is currently no DJ queue.')
					}
				}
				break;	
			case "q?": case "q list": case "room mode":
				if(botConfig.djq) {
					if($g.isQueue) {
						var message="";
						var theQueue;
						
						if($g.djQueue) {
							for(var i=0;i < $g.djQueue.length; i++) {
								theQueue=$g.djQueue[i][1];
								(message) ? message=message+', '+theQueue : message=theQueue;
							}
						}
						
						if(message=="") {
							message='There are currently no DJ\'s in the queue. Type /q+ to be the first in line!'
						} else {
							message="DJ QUEUE: "+message;
						}					
						bot.speak(message);
					} else {
						bot.speak('@'+name+' - There is currently no DJ queue. It\'s a free for all!')
					}
				}
				break;
			case "boobytrap":
				bot.speak('( x )( x )');
				break;
			case "partyboob": 
				bot.speak('( ^ )( ^ )');
				break;
			case "showusyourboobs":
				bot.speak('( * )( * )');
				break;
			case "commands": //available bot commands
				bot.speak($g.availableBotCommands);
				break;
			case "bot?": //identify the bot when someone asks
				bot.speak('It\'s me, '+bot.name+', I\'m the bot.');
				break;
		}
	   
	   //only respond to the following commands if they come from an administrative user
	   if($g.isBotAdmin) {
			if(text=="crap" || text=="miz" || text=="zou") {//lame the current song when told to
				bot.vote('down');
			}
	   }
	});
	
	bot.on('pmmed',function(data){
		var returnMessage;
		var message;
		var messageClass;
		var command;
	
		//was the pm from a room moderator?
		if($g.mods) { ($g.mods.indexOf(data.senderid)>-1) ? $g.isMod=true : $g.isMod=false; } 
		if($g.botAdmins) { ($g.botAdmins.indexOf(data.senderid)>-1) ? $g.isBotAdmin=true : $g.isbotAdmin=false; }
		
		message=data.text;//get text of pm
		message=message.split('|');//split into array
		messageClass=message[0];
		
		if(message[1]) { 
			var command=message[1];
		
			if(command.indexOf('=')>-1) {
				var tmpCommand=command.split('=');
				var paramValue=tmpCommand[1];
				command=tmpCommand[0];
			}
		}    
		
		switch(messageClass) {
			case 'battle': case 'b': //accept either battle|[command] or b|[command]
				if(botConfig.battle) {
					switch(command) {
						case "abort":
							if($g.isMod) { bot.pm(battle.abort(),data.senderid); }
							break;
						case 'init': //initializes the battle, setting all contestants to defaults/0
							if($g.isMod) { 
								var message="Battle initialization complete.";
								battle.init();
								bot.pm(message,data.senderid);
								bot.speak('The battle is on! Good luck!');
							}
							break;
						case 'roominfo': //writes out battle room info, including battle id, to console
							if($g.isMod) { 
								if(battle.info) {
									for(var i=0;i < battle.info.length; i++) {
										/*console.log(battle.info[i]);*/
									}
								} else {
									bot.pm('There is no battle currently running. Type battle|init to start one.',data.senderid);
								}
							}
							break;
						case 'info': case 'check': //displays battle details to mod via pm
							if($g.isMod) { 
								if(battle.info) {    				
									//battle.check();
									if(battle.id) { bot.pm('Battle ID: '+battle.id,data.senderid); }
									if(battle.roomId) { bot.pm('Room ID: '+battle.roomId,data.senderid); }
									if(battle.roomName) { bot.pm('Room Name: '+battle.roomName,data.senderid); }
									if(battle.dateTime) { bot.pm('Date: '+battle.dateTime,data.senderid); }
									if(battle.djs) { bot.pm('DJs: '+battle.djs,data.senderid); }
									if(battle.maxRounds) { bot.pm('Max Rounds: '+battle.maxRounds,data.senderid); }    			
								} else {
									bot.pm('There is no battle currently running. Type battle|init to start one.',data.senderid);
								}
							}
							break;
						case 'maxrounds': //set number of battle rounds; if not set, defaults to 2 in battle.init();
							if($g.isMod) { 
								battle.maxRounds=paramValue;
							}
							break;
						case 'stats': //return battle stats/standings to user via pm
							if(battle.info) {
                                if($g.isMod) {
                                    if(paramValue=="chat") { 
                                        bot.speak("CURRENT BATTLE STATS:"); 
                                        paramValue=true; 
                                    } else { paramValue=false; }
                                } else { paramValue=false; }
                                setTimeout(function(){
                                    battle.stats(data.senderid,paramValue);
                                },500);
							} else {
								returnMessage='There is no battle currently running.'
								if($g.isMod) {
									returnMessage=returnMessage+' Type battle|init to start one.'; //instruct mods on how to start a battle
								}
								bot.pm(returnMessage,data.senderid);
							}
							break;
						case 'rules': //display basic battle rules via public chat
							bot.speak('Battle rules: DJ with most points after '+battle.maxRounds+' rounds wins. PM me battle|stats for current standings.');
							bot.speak('Battle rules: Leaving the deck during the battle forfeits your spot. PM me battle|stats for current standings.');
						case 'scoring': //display scoring rules via public chat; also displays when battle|rules is executed
							bot.speak('Battle scoring: +1pt per awesome, +2pt per snag, -1pt per lame');
							break;
					}
				}
				break; 
			case 'q':
				if(botConfig.djq) {
					switch (command) {
						case 'on': 
							$g.isQueue=true;
							bot.speak('The DJ queue has been enabled. Type /q+ to get in line!');
							break;
						case 'off': 
							$g.isQueue=false;
							$g.djQueue=[];
							bot.speak('The DJ queue has been turned off. It\'s a free for all!');
							break;
						case 'rem':
							$g.queueRemove('',paramValue)//remove by name
							break;
					}
				}
				break;
			case 'echo': case '@': //enable moderator to engage in public chat
				if(botConfig.echo) {
					if($g.isMod) { 
						bot.speak(command);
					}
				}
				break;   	
			case 'djoverride': //toggle whether bot auto-dj's or not (true|false)
				if($g.isMod) { 
					switch(command){
						case 'on':	$g.djOverride=true; //blocks dj from taking stage
						case 'off':	$g.djOverride=false;//allows dj to take stage
						default:	($g.djOverride) ? $g.djOverride=false : $g.djOverride=true;
					}
                    bot.djOverride=$g.djOverride;
					bot.pm('djOverride: '+bot.djOverride,data.senderid);
				}
				break;
			case 'songstats': //toggle whether to announce song stats in public chat on song completion (true|false)
				if(botConfig.songstats) {
					if($g.isMod) { 
						($g.announceSongStats) ? $g.announceSongStats=false : $g.announceSongStats=true;
						bot.pm(($g.announceSongStats)?'Song Stats Enabled':'Song Stats Disabled',data.senderid);
					}
				}
				break;    	
			case 'awesome': case 'dance': //awesome current song
				bot.vote('up');
				break;
			case 'crap': //lame current song
				if($g.isMod) { 
					bot.vote('down');
				}
				break;
			case "profile":
				if($g.isMod) { if(command) { $g.getProfile(command); } }
				break;
			case "fan":
				if($g.isMod) { if(command) { $g.addFan(command); } }
				break;
			case 'downvotes':
				if($g.isMod) {
					var downVoteDjNames;
					var tempDjName;
					
					if($g.downVoteArray.length>0) {
						for(var i=0;$g.downVoteArray.length;i++) {
							tempDjName=$g.getDjNameById($g.downVoteArray[i]);
							(downVoteDjNames) ? downVoteDjNames+=', '+tempDjName : downVoteDjNames=tempDjName;
						}
					} else {
						downVoteDjNames='none';
					}
					bot.pm('downVoteArray: '+downVoteDjNames,data.senderid);
				}
				break;
			case 'follow':
				if(botConfig.follow) {
					if($g.isBotAdmin) { $g.follow(data.senderid); }
				}
				break;
			case 'home':
				if(botConfig.follow) {
					if($g.isBotAdmin) { $g.home(); }
				}
				break;				
			case 'usercount':
				$g.getUserCount();
				setTimeout(function(){
					bot.pm('D'+$g.botUserCount[0]+' | L'+$g.botUserCount[1]+' | T'+$g.botUserCount[2]+' | MV'+$g.botUserCount[3],data.senderid);
				} ,500);
				break;
			case 'minvote': case 'mv': //must pass as decimal representing #% of users required for bot to vote for current song
				if($g.isMod) {
					$g.pctNeededForVote=command;
					$g.getUserCount();
				}
				break;
			case 'themeset': case 'theme set': case 'set theme': case 'settheme': //case 'theme+':
				if(botConfig.theme) {
					if($g.isMod) {
						$g.setRoomTheme(command);
					}
				}
				break;
			case '+fav':
				if($g.isMod) { $g.addFavoriteRoom(); }
				break;
			case 'getbot':
				if($g.isMod) { /*console.log(bot);*/ }
				break;
			case 'mod-':
				if($g.isMod) { $g.remMod(command); }
				break;
			case 'av':
				if($g.isMod) {
					var senderId=data.senderid;
					bot.setAvatar(command,function(data){
						var returnVal='new avatar: '+command+' - '+data.success;
						bot.pm(returnVal,senderId);/*console.log(returnVal);*/
					});
				}
				break;
			case 'slide':
				if(botConfig.slide) {
					if($g.isMod) { 
						var returnMsg;
						switch (command) {
							case 'on':
								$g.slideOn=true;
								$g.slideCountArray=[];//array to keep track of songs played while slide is on
								break;
							case 'off':
								$g.slideOn=false;
								$g.slideCountArray="";//array to keep track of songs played while slide is on
								break;
							case 'limit':
								if(paramValue && !isNaN(paramValue)) {
									$g.slideCountLimit=(paramValue>0) ? paramValue : 1;
									returnMsg='Slide limit set to '+paramValue;
									bot.pm(returnMsg,data.senderid);
								} else { 
									returnMsg='Current slide limit: '+$g.slideCountLimit;
									bot.pm(returnMsg,data.senderid);
								}
								break;
						}
						if(command=="on" || command=="off") {
							returnMsg=($g.slideOn) ? "enabled ("+$g.slideCountLimit+" song limit)" : "disabled";
							bot.speak('SLIDE has been '+returnMsg+'.');
						}
					}
				}
				break;
			case "up": //make the bot a dj
				if($g.isMod) { bot.addDj(function(empty) { /*console.log('bot up');*/ }); }
				break;
			case "down": //make the bot step down from the tables
				if($g.isMod) { bot.remDj(USERID,function(empty) { /*console.log('bot down');*/ }); }
				break;
			case "skip": //make the bot skip the current song (if bot is current dj)
				if($g.isMod) { bot.stopSong(function() { /*console.log('bot skip');*/ }); }
				break;
			case "snag": //make the bot snag the current song
				if($g.isMod) { 
                   $g.snag($g.currentSong);
                }
				break;
            case "delete": //make bot delete current song from his queue
                if($g.isMod) { 
                    bot.playlistRemove();
                }
				break;
            case "playlist": //get current playlist for bot
                if($g.isMod) {
                    bot.playlistAll(function(playlist) {
                        bot.pm(playlist.list.length+' songs in my playlist.',data.senderid);
                        //console.log(playlist.list);
                    });
                }
                break;
			case 'greet': //room greetings - enable/disable/change greeting for when dj enters room
				if($g.isMod) {
                    var returnMsg;
                    console.log(command);
                    switch(command) {
                        case "on":  $g.greet=true;returnMsg="Greeting enabled";break;
                        case "off": $g.greet=false;returnMsg="Greeting disabled";break;
                        case "msg": $g.greeting=paramValue;returnMsg="Greeting changed to: "+paramValue;break;
                        case "loc": 
                            if(paramValue=="pm" || paramValue=="chat" || paramValue=="both") {
                                $g.greetloc=paramValue;
                                returnMsg="Greeting location changed to: "+paramValue;
                            } else {
                                returnMsg="'"+paramValue+"' is not a valid greeting location. Try again.";
                            }
                            break;
                    }
                    bot.pm(returnMsg,data.senderid);
                }
				break;
			default:
				bot.pm('Unknown command: '+data.text,data.senderid);
				break;
		}
	});
	
	bot.on('snagged',function(data) { //count number of listeners who snag a song
		if($g.songSnaggers.indexOf(data.userid)<0) {
			$g.songSnaggers.push(data.userid);
		}
	});
	
	bot.on('roomChanged',function(data){ //get list of room mods for later reference
		$g.mods=data.room.metadata.moderator_id;
		$g.mods=$g.mods.concat($g.botAdmins);
		console.log($g.mods);
	});
	
	/*
	battle.djs (array) = [battleId, djId, djName, ttlUp, ttlDown, ttlSnag, ttlPts, ttlSongs]
		0 battleId =  [roomId+dateTime]
		1 djId =      [DJ ID]
		2 djName =    [friendly DJ name]
		3 ttlUp =     [total awesome votes]
		4 ttlDown =   [total lame votes]
		5 ttlSnag =   [total song snags]
		6 ttlPts =    [ttlUp-ttlDown+(ttlSnag*2)]
		7 ttlSongs =  [total songs played as part of current battle]
		
	battle.info (array) = [battleId, roomId, roomName, dateTime]
		battleId =  [roomId+dateTime]
		roomId =    [room ID]
		roomName =  [friendly room name]
		dateTime =  [tt server date/time: bot.roomNow()]
	*/
	battle.init = function(pv_maxRounds) { 
		bot.roomNow(function(data){battle.dateTime=data.now;});   
		bot.roomInfo(false,function(data){
			battle.roomId=data.room.roomid;
			battle.roomName=data.room.name;
			battle.id=battle.roomId+battle.dateTime;
			battle.tempDjs=data.room.metadata.djs;
			(pv_maxRounds) ? battle.maxRounds=pv_maxRounds : (!battle.maxRounds) ? battle.maxRounds=2 : battle.maxRounds=battle.maxRounds;
			battle.djsFinished=0;
			battle.users=data.users.splice(',');
			
			//build battle info array
			battle.info=[];
				battle.info[0]=battle.id;
				battle.info[1]=battle.roomId;
				battle.info[2]=battle.roomName;
				battle.info[3]=battle.dateTime
			
			//build battle djs array	
			battle.djs=[];
			for(var i=0;i < battle.tempDjs.length; i++) {
				var tmpArray=[];
				tmpArray[0]=battle.id;//battleId
				tmpArray[1]=battle.tempDjs[i];//djId   
				tmpArray[2]="";//reserved for djName - populated below
				
				for(var ii=0;ii<battle.users.length;ii++) {
					if(battle.users[ii].userid==battle.tempDjs[i]) { tmpArray[2]=battle.users[ii].name; }//assign dj name
				}
				tmpArray[3]=0;//total awesome count
				tmpArray[4]=0;//total lame count
				tmpArray[5]=0;//total snags count
				tmpArray[6]=0;//total points
				tmpArray[7]=0;//total songs played
			 
				battle.djs[i]=tmpArray;
			}
		battle.inProgress=true;    
		});
	}

	/*
		battle.abort() - abort|discontinue current battle
	*/
	battle.abort=function() {
		var returnVal;
		if(battle.inProgress) {
			battle.inProgress=false;
			battle.djs="";
			battle.info="";
			
			returnVal="Battle has been cancelled.  PM battle|init to start a new battle.";
		} else {
			returnVal="There is no battle currently running.  PM battle|init to start a battle."
		}
		return(returnVal);
	}
	
	battle.stats=function(pv_senderid,pv_isPublic) { //return current and final battle stats to both public chat window and private console	
		for(var i=0;i < battle.djs.length; i++) {
			if(battle.djs[i][2]) { //only speak if dj has a name (name assigned on endsong of first song for each dj in battle
				
				message=battle.djs[i][2]+': '+battle.djs[i][6]+'pt | '+battle.djs[i][7]+'song';
				(pv_isPublic) ? bot.speak(message) : bot.pm(message,pv_senderid);
			}
		}
//		(pv_isPublic) ? bot.speak(message) : bot.pm(message,pv_senderid);
	}
	
	$g.magic8ball=function() {
		var returnArray=[
			"Signs point to yes.","Yes.","Reply hazy, try again.","Without a doubt.","My sources say no.",
			"As I see it, yes.","You may rely on it.","Concentrate and ask again.","Outlook not so good.",
			"It is decidedly so.","Better not tell you now.","Very doubtful.","Yes - definitely.","It is certain.",
			"Cannot predict now.","Most likely.","Ask again later.","My reply is no.","Outlook good.",
			"Don't count on it."
		]
		return(returnArray[Math.floor(Math.random() * returnArray.length)]);
	}

	$g.coinFlip=function() {
		var returnArray=[
			"Heads","Tails"
		]
		return(returnArray[Math.floor(Math.random() * returnArray.length)]);
	}

	/* rock, paper, scissors */
	$g.rps=function() {
		var returnArray=[
			"Rock","Paper","Scissors :scissors:"
		]
		return(returnArray[Math.floor(Math.random() * returnArray.length)]);
	}
	
	/* rock, paper, scissors, lizard, spock */
	$g.rpsls=function() {
		var returnArray=[
			"Rock","Paper","Scissors :scissors:","Lizard","Spock"
		]
		return(returnArray[Math.floor(Math.random() * returnArray.length)]);
	}

	$g.getFortune=function() {
		//fortunes courtesy of http://www.chinese-fortune-cookie.com/fortune-cookie-quotes.html
		var fortuneArray=[
			"There is a true and sincere friendship between you and your friends.",
			"You find beauty in ordinary things, do not lose this ability.",
			"Ideas are like children; there are none so wonderful as your own.",
			"It takes more than good memory to have good memories.",
			"A thrilling time is in your immediate future.",
			"Your blessing is no more than being safe and sound for the whole lifetime.",
			"Plan for many pleasures ahead.",
			"The joyfulness of a man prolongeth his days.",
			"Your everlasting patience will be rewarded sooner or later.",
			"Make two grins grow where there was only a grouch before.",
			"Something you lost will soon turn up.",
			"Your heart is pure, and your mind clear, and your soul devout.",
			"Excitement and intrigue follow you closely wherever you go!",
			"A pleasant surprise is in store for you.",
			"May life throw you a pleasant curve.",
			"As the purse is emptied the heart is filled.",
			"Be mischievous and you will not be lonesome.",
			"You have a deep appreciation of the arts and music.",
			"Your flair for the creative takes an important place in your life.",
			"Your artistic talents win the approval and applause of others.",
			"Pray for what you want, but work for the things you need.",
			"Your many hidden talents will become obvious to those around you.",
			"Don't forget, you are always on our minds.",
			"Your greatest fortune is the large number of friends you have.",
			"A firm friendship will prove the foundation on your success in life.",
			"Don't ask, don't say. Everything lies in silence.",
			"Look for new outlets for your own creative abilities.",
			"Be prepared to accept a wondrous opportunity in the days ahead!",
			"Fame, riches and romance are yours for the asking.",
			"Good luck is the result of good planning.",
			"Good things are being said about you.",
			"Smiling often can make you look and feel younger.",
			"Someone is speaking well of you.",
			"The time is right to make new friends.",
			"You will inherit some money or a small piece of land.",
			"Your life will be happy and peaceful.",
			"A friend is a present you give yourself.",
			"A member of your family will soon do something that will make you proud.",
			"A quiet evening with friends is the best tonic for a long day.",
			"A single kind word will keep one warm for years.",
			"Anger begins with folly, and ends with regret.",
			"Generosity and perfection are your everlasting goals.",
			"Happy news is on its way to you.",
			"He who laughs at himself never runs out of things to laugh at.",
			"If your desires are not extravagant they will be granted.",
			"Let there be magic in your smile and firmness in your handshake.",
			"If you want the rainbow, you must put up with the rain. D. Parton",
			"Nature, time and patience are the three best physicians.",
			"Strong and bitter words indicate a weak cause.",
			"The beginning of wisdom is to desire it.",
			"You will have a very pleasant experience.",
			"You will inherit some money or a small piece of land.",
			"You will live a long, happy life.",
			"You will spend old age in comfort and material wealth.",
			"You will step on the soil of many countries.",
			"You will take a chance in something in the near future.",
			"You will witness a special ceremony.",
			"Your everlasting patience will be rewarded sooner or later.",
			"Your great attention to detail is both a blessing and a curse.",
			"Your heart is a place to draw true happiness.",
			"Your ability to juggle many tasks will take you far.",
			"A friend asks only for your time, not your money.",
			"You will be invited to an exciting event.",
			"'Boobytrap' backwards is 'partyboob'", //from here down, fotunes are NOT from chinese-fortune-cookie.com
			"The fortune you seek is in another cookie.",
			"Today is probably a huge improvement over yesterday.",
			"How much deeper would the ocean be without sponges?",
			"Do :fries: go with that shake?", //from here down, fortunes came from gretchen, though not sure of source
			"A dubious friend may be an enemy in camouflage.",
			"A faithful friend is a strong defense.",
			"A feather in the hand is better than a bird in the air.",
			"A focused mind is one of the most powerful forces in the universe.",
			"A fresh start will put you on your way.",
			"A friend asks only for your time not your money.",
			"A friend is a present you give yourself.",
			"A gambler not only will lose what he has, but also will lose what he doesnít have.",
			"A golden egg of opportunity falls into your lap this month.",
			"A good beginning is half the task.",
			"A good time to finish up old tasks. ",
			"A hunch is creativity trying to tell you something.",
			"A journey must begin with a single step.",
			"A kiss makes the heart young again and wipes out the years.",
			"A leader is powerful to the degree he empowers others.",
			"A lifetime friend shall soon be made.",
			"A light heart carries you through all the hard times.",
			"A man can fail many times, but he isn't a failure until he gives up.",
			"A new outlook brightens your image and brings new friends.",
			"A new perspective will come with the new year. ",
			"A person of words and not deeds is like a garden full of weeds.",
			"A pleasant surprise is waiting for you.",
			"A smile is your personal welcome mat.",
			"A smooth long journey! Great expectations.",
			"A soft voice may be awfully persuasive.",
			"A truly rich life contains love and art in abundance.",
			"Accept something that you cannot change, and you will feel better.",
			"Adventure can be real happiness.",
			"Advice is like kissing. It costs nothing and is a pleasant thing to do.",
			"Advice when most needed, is least heeded.",
			"Advice, when most needed, is least heeded.",
			"All the answers you need are right there in front of you!",
			"All the effort you are making will ultimately pay off.",
			"All the troubles you have will pass away very quickly.",
			"All the world may not love a lover but they will be watching him.",
			"All will go well with your new project.",
			"All your hard work will soon pay off.",
			"Allow compassion to guide your decisions.",
			"Allow your mind to absorb new knowledge.",
			"An agreeable romance might begin to take on the appearance.",
			"An hour with friends is worth more than ten with strangers.",
			"An important person will offer you support.",
			"An inch of time is an inch of gold.",
			"Any activity becomes creative when the doer cares about doing it right, or better.",
			"As every thread of gold is valuable, so is every moment of time.",
			"Assert yourself, your ideas are worthwhile.",
			"Be careful or you could fall for some tricks today.",
			"Beauty in its various forms appeals to you. ",
			"Because you demand more from yourself, others respect you deeply.",
			"Before you receive, you must give.",
			"Before you wonder, Am I doing things right, ask Am I doing the right things?",
			"Believe in yourself and others will too.",
			"Believe it can be done.",
			"Better ask twice than lose yourself once.",
			"Better to face danger than be always in fear.",
			"Bide your time, for success is near.",
			"Carve your name on your heart and not on marble.",
			"Change is happening in your life, so go with the flow!",
			"Character is who you are when no one is watching.",
			"Competence like yours is underrated.",
			"Congratulations! You are on your way.",
			"Constant grinding can turn an iron rod into a needle.",
			"Could I get some directions to your heart? ",
			"Courage is the mastery of fear - not the absence of fear.",
			"Courtesy begins in the home.",
			"Courtesy is contagious.",
			"Curiosity kills boredom. Nothing can kill curiosity.",
			"Dedicate yourself with a calm mind to the task at hand.",
			"Depart not from the path which fate has you assigned.",
			"Determination is what you need now.",
			"Disbelief destroys the magic.",
			"Distance yourself from the vain.",
			"Do not be intimidated by the eloquence of others.",
			"Do not let ambitions overshadow small success.",
			"Do not make extra work for yourself.",
			"Do not underestimate yourself. Human beings have unlimited potentials.",
			"Donít be discouraged, because every wrong attempt discarded is another step forward.",
			"Donít confuse recklessness with confidence. ",
			"Don't just spend time. Invest it.",
			"Don't just think, act!",
			"Don't let friends impose on you, work calmly and silently.",
			"Don't let the past and useless detail choke your existence.",
			"Don't let your limitations overshadow your talents.",
			"Don't worry; prosperity will knock on your door soon.",
			"Don't be afraid to take that big step.",
			"Each day, compel yourself to do something you would rather not do.",
			"Education is the ability to meet lifeís situations.",
			"Emulate what you admire in your parents. ",
			"Emulate what you respect in your friends.",
			"Enjoy the lighter things in life, deeper joys will follow.",
			"Enjoy what you have! Never mind fame and power.",
			"Every flower blooms in its own sweet time.",
			"Every wise man started out by asking many questions.",
			"Everyday in your life is a special occasion.",
			"Everywhere you choose to go, friendly faces will greet you.",
			"Failure is the chance to do better next time.",
			"Failure is the mother of success.",
			"Feeding a cow with roses does not get extra appreciation.",
			"For hate is never conquered by hate. Hate is conquered by love.",
			"Fortune Not Found: Abort, Retry, Ignore?",
			"From listening comes wisdom and from speaking repentance.",
			"From now on your kindness will lead you to success.",
			"Get your mind set, confidence will lead you on.",
			"Go take a rest; you deserve it.",
			"Good luck is the result of good planning.",
			"Good news will be brought to you by mail.",
			"Good news will come to you by mail.",
			"Good to begin well, better to end well.",
			"Happiness begins with facing life with a smile and a wink.",
			"Happiness will bring you good luck.",
			"Happy life is just in front of you.",
			"Hard words break no bones, fine words butter no parsnips.",
			"Have a beautiful day.",
			"He who expects no gratitude shall never be disappointed. ",
			"He who knows he has enough is rich.",
			"Help! Iím being held prisoner in a chinese bakery!",
			"Hone your competitive instincts.",
			"Hope is the most precious treasure to a person.",
			"How you look depends on where you go.",
			"I learn by going where I have to go.",
			"If a true sense of value is to be yours it must come through service.",
			"If certainty were truth, we would never be wrong.",
			"If you continually give, you will continually have.",
			"If you look in the right places, you can find some good offerings.",
			"If you think you can do a thing or think you canít do a thing, youíre right.",
			"If your desires are not extravagant, they will be granted.",
			"If your desires are not to extravagant they will be granted. ",
			"Impossible is a word only to be found in the dictionary of fools.",
			"In order to take, one must first give.",
			"In the end all things will be known.",
			"It could be better, but its [sic] good enough.",
			"It is better to ask some questions than to know all the answers.",
			"It is better to deal with problems before they arise.",
			"It is honorable to stand up for what is right, however unpopular it seems.",
			"It is worth reviewing some old lessons.",
			"It takes courage to admit fault.",
			"Itís time to get moving. Your spirits will lift accordingly.",
			"Keep true to the dreams of your youth.",
			"Keep your face to the sunshine and you will never see shadows.",
			"Keep your plans secret for now.",
			"Lady luck will soon visit you.",
			"Let the spirit of adventure set the tone.",
			"Let the world be filled with tranquility and goodwill.",
			"Lies and sorrow may float through the air, but truth and happiness live inside yourself.",
			"Listen not to vain words of empty tongue.",
			"Listen to everyone. Ideas come from everywhere.",
			"Living with a commitment to excellence shall take you far.",
			"Long life is in store for you.",
			"Love is a warm fire to keep the soul warm.",
			"Love is like sweet medicine, good to the last drop.",
			"Love lights up the world.",
			"Love truth, but pardon error. ",
			"Man is born to live and not prepared to live.",
			"Many will travel to hear you speak.",
			"Meditation with an old enemy is advised.",
			"Miles are covered one step at a time.",
			"Nature, time and patience are the three great physicians.",
			"Never fear! The end of something marks the start of something new.",
			"New ideas could be profitable.",
			"New people will bring you new realizations, especially about big issues. ",
			"No man is a failure who is enjoying life.",
			"No one can walk backwards into the future.",
			"Now is a good time to buy stock.",
			"Now is the time to go ahead and pursue that love interest!",
			"Now is the time to try something new",
			"One that would have the fruit must climb the tree.",
			"Open up your mind. Let your fantasies unwind.",
			"Others can help you now.",
			"Patience is a key to joy.",
			"Pennies from heaven find their way to your doorstep this year!",
			"People are attracted by your Delicate[sic] features.",
			"People find it difficult to resist your persuasive manner.",
			"Perhaps youíve been focusing too much on saving.",
			"Physical activity will dramatically improve your outlook today.",
			"Place special emphasis on old friendship.",
			"Practice makes perfect.",
			"Pray for what you want, but work for the things you need.",
			"Progess always involves risk.",
			"Protective measures will prevent costly disasters.",
			"Put your mind into planning today. Look into the future.",
			"Remember to share good fortune as well as bad with your friends.",
			"Rest has a peaceful effect on your physical and emotional health.",
			"Resting well is as important as working hard.",
			"Romance moves you in a new direction.",
			"Say hello to others. You will have a happier day.",
			"Self-knowledge is a life long process.",
			"Share your joys and sorrows with your family.",
			"Share your joys and sorrows with your family.",
			"Sloth makes all things difficult; industry all easy.",
			"Small confidences mark the onset of a friendship.",
			"Smile! A frown may turn others away.",
			"Society prepares the crime; the criminal commits it.",
			"Someone you care about seeks reconciliation.",
			"Sometimes the object of the journey is not the end, but the journey itself.",
			"Sometimes traveling to a new place leads to great transformation.",
			"Soon life will become more interesting.",
			"Soon, you'll have a chance at a profitable transaction.",
			"Stand tall. Donít look down upon yourself. ",
			"Stop searching forever, happiness is just next to you.",
			"Success is a journey, not a destination.",
			"Success is going from failure to failure without loss of enthusiasm.",
			"Take care and sensitivity you show towards others will return to you.",
			"Take the high road.",
			"The austerity you see around you covers the richness of life like a veil.",
			"The best prediction of future is the past.",
			"The change you started already have far-reaching effects. Be ready.",
			"The change you started already have far-reaching effects. Be ready.",
			"The essential conditions of everything you do must be choice, love, and passion.",
			"The first man gets the oyster, the second man gets the shell.",
			"The harder you work, the luckier you get.",
			"The home is the chief school of human virtues.",
			"The intention is not to see through people, but rather to see people through.",
			"The night life is for you.",
			"The one that recognizes the illusion does not act as if it is real.",
			"The only people who never fail are those who never try.",
			"The person who will not stand for something will fall for anything.",
			"The philosophy of one century is the common sense of the next.",
			"The saints are the sinners who keep on trying.",
			"The secret to good friends is no secret to you. ",
			"The small courtesies sweeten life, the greater ennoble it.",
			"The smallest deed is better than the biggest intention.",
			"The smart thing to do is to begin trusting your intuitions.",
			"The strong person understands how to withstand substantial loss.",
			"The sure way to predict the future is to invent it.",
			"The time has come to allow your heart to guide you.",
			"The truly generous share, even with the undeserving.",
			"The two hardest things to handle in life are failure and success.",
			"The value lies not within any particular thing, but in the desire placed on that thing.",
			"The weather is wonderful. ",
			"There is no mistake so great as that of being always right.",
			"There is no wisdom greater than kindness. ",
			"There is not greater pleasure than seeing your lived (sic) ones prosper.",
			"Thereís no such thing as an ordinary cat.",
			"Things donít just happen; they happen just.",
			"Those who care will make the effort.",
			"Time is precious, but truth is more precious than time",
			"To know oneself, one should assert oneself.",
			"To understand a man's mind, listen to his words.",
			"Today is the conserve yourself, as things just wonít budge.",
			"Today, your mouth might be moving but no one is listening.",
			"Tonight you will be blinded by passion.",
			"Use your eloquence where it will do the most good.",
			"Versatility is one of your outstanding traits.",
			"Watch your relations with other people carefully, be reserved.",
			"Wealth is not a matter of intelligence - it's a matter of inspiration.",
			"Welcome change.",
			"Welcomeî is a powerful word.",
			"Well done is better than well said.",
			"What is hidden in an empty box?",
			"Whatís yours in mine, and whatís mine is mine.",
			"When your heart is pure, your mind is clear.",
			"Wise men learn more from fools than fools from the wise.",
			"Wish you happiness.",
			"With integrity and consistency, your credits are piling up.",
			"You always bring others happiness.",
			"You are a person of another time.",
			"You are a talented storyteller. ",
			"You are admired by everyone for your talent and ability.",
			"You are almost there.",
			"You are always entertaining and delightful.",
			"You are busy, but you are happy.",
			"You are generous to an extreme and always think of the other fellow.",
			"You are going to have some new clothes. ",
			"You are in good hands this evening.",
			"You are modest and courteous.",
			"You are never selfish with your advice or your help.",
			"You are next in line for promotion in your firm.",
			"You are offered the dream of a lifetime. Say yes!",
			"You are open-minded and quick to make new friends. ",
			"You are solid and dependable.",
			"You are soon going to change your present line of work.",
			"You are talented in many ways.",
			"You are the master of every situation. ",
			"You are very expressive and positive in words, act and feeling.",
			"You are working hard.",
			"You begin to appreciate how important it is to share your personal beliefs.",
			"You desire recognition and you will find it.",
			"You don't get in life what you want; you get in life what you are.",
			"You have a deep appreciation of the arts and music.",
			"You have a deep interest in all that is artistic.",
			"You have a friendly heart and are well admired. ",
			"You have a shrewd knack for spotting insincerity.",
			"You have a unique personality.",
			"You have a yearning for perfection.",
			"You have an active mind and a keen imagination.",
			"You have an ambitious nature and may make a name for yourself.",
			"You have an unusual equipment for success, use it properly.",
			"You have exceeded what was expected.",
			"You have the power to write your own fortune.",
			"You have yearning for perfection.",
			"You know where you are going and how to get there.",
			"You look pretty.",
			"You love challenge.",
			"You love chinese food.",
			"You make people realize that there exist other beauties in the world.",
			"You may lack ambition, but not the ability to succeed.",
			"You never hesitate to tackle the most difficult problems. ",
			"You seek to shield those you love and like the role of provider. ",
			"You should be able to make money and hold on to it.",
			"You should be able to undertake and complete anything.",
			"You understand how to have fun with others and to enjoy your solitude.",
			"You will always be surrounded by true friends.",
			"You will always get what you want through your charm and personality.",
			"You will always have good luck in your personal affairs.",
			"You will attract cultured and artistic people to your home.",
			"You will be a great success both in the business world and society. ",
			"You will be advanced socially, without any special effort.",
			"You will be blessed with longevity.",
			"You will be successful in your work.",
			"You will be traveling and coming into a fortune.",
			"You will be unusually successful in business.",
			"You will become a great philanthropist in your later years.",
			"You will become more and more wealthy.",
			"You will enjoy good health.",
			"You will enjoy good health; you will be surrounded by luxury.",
			"You will find great contentment in the daily, routine activities.",
			"You will have a fine capacity for the enjoyment of life.",
			"You will have gold pieces by the bushel.",
			"You will have many important meetings, visits, and chance encounters.",
			"You will inherit a large sum of money.",
			"You will live a long, prosperous life.",
			"You will make a name for yourself.",
			"You will make change for the better.",
			"You will make many changes before settling satisfactorily.",
			"You will move to a wonderful new home within the year.",
			"You will soon be involved in many gatherings, parties and communications.",
			"You will soon be surrounded by good friends and laughter.",
			"You will take a chance in something in near future.",
			"You will travel far and wide, both pleasure and business.",
			"Your abilities are unparalleled.",
			"Your ability is appreciated.",
			"Your ability to juggle many tasks will take you far.",
			"Your biggest virtue is your modesty.",
			"Your career is moving more and more towards service to others.",
			"Your careful nature will bring you financial success.",
			"Your character can be described as natural and unrestrained.",
			"Your difficulties will strengthen you.",
			"Your dreams are never silly; depend on them to guide you.",
			"Your dreams are worth your best efforts to achieve them.",
			"Your energy returns and you get things done.",
			"Your family is young, gifted and attractive.",
			"Your first love has never forgotten you.",
			"Your happiness is before you, not behind you! Cherish it.",
			"Your happiness is intertwined with your outlook on life.",
			"Your hard work will payoff today.",
			"Your heart will always make itself known through your words.",
			"Your home is the center of great love.",
			"Your ideals are well within your reach.",
			"Your infinite capacity for patience will be rewarded sooner or later.",
			"Your leadership qualities will be tested and proven.",
			"Your life will be happy and peaceful.",
			"Your life will get more and more exciting.",
			"Your love life will be happy and harmonious.",
			"Your love of music will be an important part of your life.",
			"Your loyalty is a virtue, but not when it ís wedded with blind stubbornness.",
			"Your luck will be changed today.",
			"Your mind is creative, original and alert.",
			"Your mind is your greatest asset.",
			"Your quick wits will get you out of a tough situation.",
			"Your success will astonish everyone.",
			"Your talents will be recognized and suitably rewarded.",
			"Your work interests can capture the highest status or prestige.",
			"You don\'t need an excuse. You just need a moment",
            "Failure is the path lease persistence."
		]
		 return(fortuneArray[Math.floor(Math.random() * fortuneArray.length)]);
	}

	/*
		$g.getLinks()
	*/
	$g.getLinks=function(){
		var returnArray=[
			"http://goo.gl/tiMzq" //auto-awesome page on siteshelp.kccloudsolutions.com
		]
		//return(returnArray[Math.floor(Math.random() * returnArray.length)]);
		return("No links available at this time.");
	}
	
	/*
		$g.getRoulette()
	*/
	$g.getRoulette=function() {
		//http://en.wikipedia.org/wiki/Roulette
		var returnArray;
		var arrayRoulette=[
			[0,"Green"],[00,"Green"],[1,"Red"],[2,"Black"],[3,"Red"],[4,"Black"],[5,"Red"],[6,"Black"],
			[7,"Red"],[8,"Black"],[9,"Red"],[10,"Black"],[11,"Black"],[12,"Red"],[13,"Black"],[14,"Red"],
			[15,"Black"],[16,"Red"],[17,"Black"],[18,"Red"],[19,"Red"],[20,"Black"],[21,"Red"],[22,"Black"],
			[23,"Red"],[24,"Black"],[25,"Red"],[26,"Black"],[27,"Red"],[28,"Black"],[29,"Black"],[30,"Red"],
			[31,"Black"],[32,"Red"],[33,"Black"],[34,"Red"],[35,"Black"],[36,"Red"]
		]
		returnArray=arrayRoulette[Math.floor(Math.random() * arrayRoulette.length)];
		return(returnArray[1]+' '+returnArray[0]);
	}

	/*
		$g.getLotto() {
	*/	
	$g.getLotto=function(pv_maxNum,pv_maxMegaNum,pv_ballType) {
		var theNumbers="";
		var numbersArray=[];
		var returnVal=[];
		var mbArray=[];
		
		//first 5 numbers...
		for(var i=1;i<pv_maxNum+1;i++) { numbersArray.push(i); }
		for(var i=1;i<6;i++) { returnVal.push(numbersArray.splice([Math.floor(Math.random()*numbersArray.length)],1)); }
		
		if(pv_ballType) { //if ball type is specified, grab 5 "white" balls and 1 "mega/power" ball
			returnVal=returnVal.toString(); 
			for(var i=1;i<pv_maxMegaNum+1;i++) { mbArray.push(i); }
			returnVal=returnVal+' '+pv_ballType+mbArray.splice([Math.floor(Math.random()*mbArray.length)],1);
		} else { //otherwise, grab a 6th "white" ball
			returnVal.push(numbersArray.splice([Math.floor(Math.random()*numbersArray.length)],1));
			returnVal=returnVal.toString();
		}
		
		//return...
        return(returnVal);
	}

	/*
		$g.follow() - moves bot to room where bot admin is currently located
		-	pv_id = id of bot admin initiating the follow command
	*/
	$g.follow=function(pv_id){
		bot.stalk(pv_id,true,function(djInfo){
			bot.roomRegister(djInfo.room.roomid,function(callback){ });
		});
	}
	
	/*
		$g.home() - moves bot to "home" room
	*/
	$g.home=function(){
		bot.roomRegister(botConfig.roomid,function(callback){ });
	}
	
	/*
		$g.isDjing() - returns true|false based on whether dj is currently on stand or not
	*/
	$g.isDjing=function(pv_djId) {
		$g.isDjingReturnVal=false;
		bot.roomInfo(false,function(roomData){		
			for(var i=0;i<roomData.room.metadata.djs.length;i++){
				if(pv_djId==roomData.room.metadata.djs[i]) {
					$g.isDjingReturnVal=true;
					return($g.isDjingReturnVal);
					break;
				} else {
					$g.isDjingReturnVal=false;
				}
			}
		});
		return($g.isDjingReturnVal);
	}
	
	$g.queueAdd=function(pv_djId, pv_djName) {
		var alreadyInQueue, queuePosition;
		var returnVal;
		var djInfo=pv_djId+'|'+pv_djName;
		
		if(!$g.djQueue) { $g.djQueue=[]; } //create djQueue array, if necessary
		
		for(var i=0;i < $g.djQueue.length; i++) {
			if($g.djQueue[i][0]==pv_djId) { 
				alreadyInQueue=true;
				queuePosition=i;
				break; 
			}
		}
	
		if(alreadyInQueue) { 
			returnVal="existing|"+queuePosition; 
		} else { 
			returnVal=$g.djQueue.push([pv_djId,pv_djName])-1;
			returnVal="new|"+returnVal;			
		}
		return(returnVal);
	}
	
	$g.queueRemove=function(pv_djId, pv_djName) {		
		if($g.djQueue) {
			for(var i=0;i < $g.djQueue.length; i++) {
				if($g.djQueue[i][0]==pv_djId || $g.djQueue[i][1]==pv_djName) { 
					$g.djQueue.splice(i,1);
					return true;
				}
			}
		}
	}
	
	$g.addFavoriteRoom=function(){
		bot.roomInfo(false,function(roomData){
			var roomId=roomData.room.roomid;
			var roomName=roomData.room.name;
			
			bot.addFavorite(roomId,function() {
				/*console.log('New favorite room: '+roomId+'--'+roomName);*/
			});
		});
	}

	$g.getUserCount=function(){
		bot.roomInfo(false,function(roomData){	
			var currentDjs=roomData.room.metadata.djcount;
			var currentListeners=roomData.room.metadata.listeners-roomData.room.metadata.djcount;//everyone but current dj
			var currentTotal=roomData.room.metadata.listeners;
			var pctNeededForVote;
			pctNeededForVote=($g.pctNeededForVote) ? $g.pctNeededForVote : 0.1;
			var minVotesNeeded=Math.round((currentTotal-1)*pctNeededForVote);
			minVotesNeeded=(minVotesNeeded<1) ? 1 : minVotesNeeded;
			
			$g.botUserCount=[];//array to capture current room attendance [djs,listeners,total,min reqd for vote]
			$g.botUserCount.push(currentDjs);
			$g.botUserCount.push(currentListeners);
			$g.botUserCount.push(currentTotal);	
			$g.botUserCount.push(minVotesNeeded);			
		});	
	}

	/*
		$g.getMods() 
		- Returns list of room mods
	*/
	$g.getMods=function() {
		bot.roomInfo(false,function(roomData){
			var roomMods=roomData.room.metadata.moderator_id;
			var newRoomMods="";
			var consoleRoomMods="";

			for(var i=0;i<roomMods.length;i++) {
				bot.getProfile(roomMods[i], function(profileData){
					(newRoomMods) ? newRoomMods+=', '+profileData.name : newRoomMods=profileData.name;
				});
			}
			setTimeout(function(){
				bot.speak('Room Mods: '+newRoomMods);
			},500);
		});
	}

	/*
		$g.getLast()
		- speaks last X songs played
	*/
	$g.getLast=function(pv_number) {
		bot.roomInfo(true,function(roomData){
			var returnVal;
			var songLog=roomData.room.metadata.songlog;

			for(var i=0;i<pv_number;i++) {
				var songDj=songLog[i].djname;
				var songName=songLog[i].metadata.song;
				var songAlbum=songLog[i].metadata.album;
				var songArtist=songLog[i].metadata.artist;
				
				returnVal=songArtist+" | "+songName+" | "+songDj;
				bot.speak(returnVal);
			}
		});
	}
		
	/*
		$g.getRoomTheme()
		- speaks the current room theme
	*/
	$g.getRoomTheme=function(pv_isNew) {
		var returnVal=(pv_isNew) ? "NEW THEME: " : "THEME: ";
		if(!$g.roomTheme || $g.roomTheme=='') {
			returnVal+='Open - Play anything!';
		} else {
			returnVal+=$g.roomTheme;
		}
		bot.speak(returnVal);
	}

	/*
		$g.setRoomTheme(pv_newTheme)
		- speaks the current room theme
	*/
	$g.setRoomTheme=function(pv_newTheme) {
		$g.roomTheme=(isNaN(pv_newTheme)) ? pv_newTheme : $g.arrayRoomThemes[pv_newTheme-1];
		$g.getRoomTheme(true);
	}
			
	/*
		$g.remMod()
	*/
	$g.remMod=function(pv_modName){
//		bot.getUserId(pv_modName,function(idData) {
//			console.log(idData.userid);
//			bot.remModerator('',function(){
//				console.log('Mod Removed: '+pv_modName);
//			});
//		});
	}

	$g.getDjNameById=function(pv_id) {	
		bot.getProfile(pv_id,function(profileData){
			return(profileData.name);
		});
	}
	
	$g.getProfile=function(pv_id) {	
		bot.getProfile(pv_id,function(profileData){
			/*console.log(profileData);*/
		});
	}

	$g.addFan=function(pv_id) {
		bot.becomeFan(pv_id,function(fanData) {
			/*console.log('now a fan of '+pv_id);*/
		});
	}

    $g.snag=function(pv_songId) {
        bot.playlistAll(function(playlist) { //get the list of the songs
            bot.playlistAdd(pv_songId, playlist.list.length); // Use the length so that it gets added to the end of the list.
        });
        bot.snag(); // This adds the heart you see on the interface
    }
    
	/*
		$g.bootBanned()
	*/
	$g.bootBanned=function(pv_userId) {
		var bootReason="Doesn\'t play nice with others.";
		for(var i=0;i<$g.bannedUsers.length;i++) {
			if($g.bannedUsers[i]==pv_userId) {
				bot.bootUser(pv_userId,bootReason,function(data){
					/*console.log('banned user booted: '+pv_userId);*/
				});
			}
		}
	}

	/*
		$g.slideCurrentStats() - Retrieves array index for slide history
		-	returns current song count for dj's on the stand if slide is on
	*/
	$g.slideCurrentStats=function() {
		var currentSlideStats;
		var dj1,dj2,dj3,dj4,dj5;

		if($g.slideOn) {
			var slideDjCount=$g.slideCountArray.length;
			if(slideDjCount>0) {
				currentSlideStats="Slide ("+$g.slideCountLimit+")";
				for(var i=0;i<slideDjCount;i++){
				    switch($g.slideCountArray[i][0]) {
				        case 0: dj1=$g.slideCountArray[i][2];break;
				        case 1: dj2=$g.slideCountArray[i][2];break;
				        case 2: dj3=$g.slideCountArray[i][2];break;
				        case 3: dj4=$g.slideCountArray[i][2];break;
				        case 4: dj5=$g.slideCountArray[i][2];break;
				    }
				}
				dj1=(dj1) ? " "+dj1 : " 0";
				dj2=(dj2) ? " "+dj2 : " 0";
				dj3=(dj3) ? " "+dj3 : " 0";
				dj4=(dj4) ? " "+dj4 : " 0";
				dj5=(dj5) ? " "+dj5 : " 0";
				currentSlideStats=currentSlideStats+dj1+dj2+dj3+dj4+dj5;
			} else {
				currentSlideStats="No slide stats yet. Check back after this song.";
			}
			return(currentSlideStats);
		}
	}
	
	/*
		$g.slideGetDjIndex - Retrieves array index for slide history
		-	used to keep array clean when a dj leaves the stand
	*/
	$g.slideGetDjIndex=function(pv_djId) {
		var returnVal;
		if($g.slideCountArray) {
			for(var i=0;i<$g.slideCountArray.length;i++){
				if($g.slideCountArray[i][1].indexOf(pv_djId)>-1) {
					var returnVal=i;
					break;
				}
			}	
		} else {
			returnVal=-1;
		}
		return(returnVal);
	}		
	/*
		"slide" feature
		- if current dj has played # songs or greater, tell them to leave the stage after current song
		- if they don't leave the stage, kick them off.
		- this allows everyone in the room to have a chance to dj
		
		$g.slideCountArray[ 0=djDeckPosition , 1=djId , 2=slideCount ] 
	*/
	$g.slideCountLimit = (botConfig.slidecount) ? botConfig.slidecount : 1; //set default song limit
	$g.slide=function(pv_djId,pv_djDeckPosition,pv_djName) { //at conclusion of song, rem_dj() (they can immediately step back up... for now)
		if($g.slideOn) {
			var djIndex=$g.slideGetDjIndex(pv_djId);
			if(djIndex>-1 && djIndex!="undefined") {
				$g.slideCountArray[djIndex][2]=$g.slideCountArray[djIndex][2]+1;
				$g.slideCountArray[djIndex][0]=pv_djDeckPosition;
				var slideCount=$g.slideCountArray[djIndex][2];
			} else {
				$g.slideCountArray.push([pv_djDeckPosition,pv_djId,1]);
			}

			$g.slideCountArray.sort();//sort by djDeckPosition
			djIndex=$g.slideGetDjIndex(pv_djId);//re-sort array
						
			if(slideCount>=$g.slideCountLimit) {
				var returnMsg=($g.slideCountLimit>1) ? $g.slideCountLimit+" songs" : $g.slideCountLimit+" song";
				bot.remDj(pv_djId,function(data) { /*console.log('SLIDE: DJ removed');*/ });
				bot.speak('@'+pv_djName+' - Slide is on, which means you play '+returnMsg+' then step down. Feel free to step back up at any time. Thanks for spinning!');
				$g.slideCountArray.splice(djIndex,1);
			}
			bot.speak($g.slideCurrentStats());
		}
	}